import { createSlice, current } from '@reduxjs/toolkit'
import { storage } from '../../utils'

const { getItem } = storage

const tabSlice = createSlice({
  name: 'tab',
  initialState: {
    //菜单是否展开
    isCollapse: false,
    // 菜单
    menu: getItem('menu') ?? [],
    // tag所使用的menu
    tabList: [
      {
        path: '/',
        name: 'home',
        label: '首页'
      }
    ],
    currentMenu: {}
  },
  reducers: {
    // 展开和收起
    collapseMenu: state => {
      state.isCollapse = !state.isCollapse
    },
    // 保存menu
    storeMenu: (state, { payload: val }) => {
      state.menu = val
    },
    selectMenuList: (state, { payload: val }) => {
      if (val.name !== 'home') {
        state.currentMenu = val
        let result = state.tabList.findIndex(item => item.name == val.name)
        if (result !== -1) return
        state.tabList.push(val)
      } else if (val.name === 'home') {
        state.currentMenu = {}
      }
    },
    //关闭tag
    closeTab: (state, { payload: val }) => {
      let res = state.tabList.findIndex(item => item.name == val.name)
      state.tabList.splice(res, 1)
      state.currentMenu = val
    },
    selectCurrentMenu: (state, { payload: val }) => {
      if (val.name === 'home') {
        state.currentMenu = {}
      } else {
        state.currentMenu = val
      }
    },
    //清空数据
    clearData: state => {
      state.isCollapse = false
      state.menu = []
      state.tabList = [
        {
          path: '/',
          name: 'home',
          label: '首页'
        }
      ]
      state.currentMenu = {}
    }
  }
})

export const { collapseMenu, storeMenu, selectMenuList, closeTab, selectCurrentMenu, clearData } =
  tabSlice.actions
export default tabSlice.reducer
